package com.fit.dao.professor;

import java.util.List;

import org.apache.tapestry5.annotations.Log;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import com.fit.entities.professor.Professor;
import com.fit.entities.user.User;
import com.fit.services.Authenticator;

public class ProfessorDAOImpl implements ProfessorDAO {

	@Inject
	private Session session;

	@Inject
	private Authenticator authenticator;

	public User getUser() {
		if (authenticator.isLoggedIn()) {
			return authenticator.getLoggedUser();
		}
		return null;
	}
	
	@Log
	public boolean save(Professor newProfessor) {
		if (newProfessor != null) {
			session.save(newProfessor);
			return true;
		}
		return false;
	}

	@Log
	public boolean delete(Professor professor) {
		if (professor != null) {
			session.delete(professor);
			return true;
		}
		return false;
	}

	@Log
	public boolean update(Professor professor) {
		if (professor != null) {
			session.update(professor);
			return true;
		}
		return false;
	}

	@Log
	public List findAll() {
		return session.createCriteria(Professor.class).list();
	}

	@Log
	public boolean deleteByID(Long id) {
		Professor u = findByID(id);
		if (u != null) {
			delete(u);
			return true;
		}
		return false;
	}

	@Log
	public Professor findByID(Long id) {
		if (id != null) {
			return (Professor) session.get(Professor.class, id);
		}
		return null;
	}

	@Log
	public Professor findByFirstNameAndLastName(String firstName, String lastName) {
		if (firstName == null || lastName == null) {
			return null;
		}

		if (firstName.equals("") || lastName.equals("")) {
			return null;
		}

		List l = session.createCriteria(Professor.class)
				.add(Restrictions.eq("lastName", lastName))
				.add(Restrictions.eq("firstName", firstName)).list();
		Professor u = null;
		if (l != null) {
			if (l.size() > 0) {
				u = (Professor) l.get(0);
			}
		}
		return u;
	}
	public List findByUser() {
		return session.createCriteria(Professor.class).add(Restrictions.eq("professorId", getUser())).list();
	}
}
